from flask import current_app
from app import db, cache
from app.common.enums import AuthPermissionType, AuthRoleStatus
from app.models import AuthPermission, AuthRole, AuthUserRole

logger = current_app.logger


@cache.memoize(timeout=60)
def user_permission_all(user_id: int) -> list[AuthPermission]:
    """用户完整权限列表
    user_id：用户id
    """
    logger.debug('用户完整权限列表')
    sql = f'''SELECT ap.* FROM auth_permission ap 
            LEFT JOIN auth_user_permission aup ON aup.permission_id=ap.id
            WHERE aup.user_id={user_id} 
            AND ap.is_enabled=1 
            UNION
            SELECT ap.* FROM auth_permission ap
            LEFT JOIN auth_role_permission arp ON arp.permission_id=ap.id
            WHERE arp.role_id IN(
                SELECT role_id FROM auth_user_role WHERE user_id={user_id}
            )'''
    permission_rows = list(db.session.execute(sql))
    permission_list = list()
    for permission in permission_rows:
        p_type_enum = AuthPermissionType.__getitem__(permission[6])
        permission_list.append(AuthPermission(
            create_at=permission[0],
            update_at=permission[1],
            id=permission[2],
            p_code=permission[3],
            p_name=permission[4],
            p_expression=permission[5],
            p_type=p_type_enum.value,
            is_enabled=(permission[7] == 0),
            description=permission[8],
        ))
    return permission_list


@cache.memoize(timeout=60)
def user_role(user_id: int) -> list[AuthRole]:
    """用户拥有角色"""
    logger.debug('用户拥有角色')
    user_role_list: list = AuthUserRole.query.filter(AuthUserRole.user_id == user_id).all()
    if user_role_list and len(user_role_list) > 0:
        # 提取角色id，然后查询用户角色表
        user_role_ids = [role.role_id for role in user_role_list]
        role_list = AuthRole.query.filter(
            AuthRole.id.in_(user_role_ids),
            AuthRole.role_status == AuthRoleStatus.enabled.name
        ).all()
        return role_list
    return []
